import { getUserInfo, setUserInfo } from './auth';

const POINTS_HISTORY_KEY = 'mall_points_history';

// 积分变动类型
export const POINTS_TYPES = {
  REGISTER: 'register',
  ORDER: 'order',
  REVIEW: 'review',
  SIGN_IN: 'sign_in',
  USE: 'use'
};

// 积分变动描述
export const POINTS_DESC = {
  [POINTS_TYPES.REGISTER]: '注册奖励',
  [POINTS_TYPES.ORDER]: '购物奖励',
  [POINTS_TYPES.REVIEW]: '评价奖励',
  [POINTS_TYPES.SIGN_IN]: '签到奖励',
  [POINTS_TYPES.USE]: '积分使用'
};

// 获取积分历史
export const getPointsHistory = () => {
  const history = localStorage.getItem(POINTS_HISTORY_KEY);
  return history ? JSON.parse(history) : [];
};

// 保存积分历史
export const setPointsHistory = (history) => {
  localStorage.setItem(POINTS_HISTORY_KEY, JSON.stringify(history));
};

// 添加积分记录
export const addPointsRecord = (type, points, description = '') => {
  const userInfo = getUserInfo();
  if (!userInfo) return false;
  
  const history = getPointsHistory();
  const record = {
    id: Date.now(),
    type,
    points,
    description: description || POINTS_DESC[type],
    createTime: Date.now(),
    userId: userInfo.id
  };
  
  history.unshift(record);
  // 只保留最近100条记录
  const newHistory = history.slice(0, 100);
  setPointsHistory(newHistory);
  
  return record;
};

// 增加积分
export const addPoints = (points, type, description = '') => {
  const userInfo = getUserInfo();
  if (!userInfo) return false;
  
  const newPoints = (userInfo.points || 0) + points;
  const updatedUser = { ...userInfo, points: newPoints };
  setUserInfo(updatedUser);
  
  // 记录积分变动
  addPointsRecord(type, points, description);
  
  return newPoints;
};

// 使用积分
export const usePoints = (points, description = '积分抵扣') => {
  const userInfo = getUserInfo();
  if (!userInfo || (userInfo.points || 0) < points) {
    return false;
  }
  
  const newPoints = userInfo.points - points;
  const updatedUser = { ...userInfo, points: newPoints };
  setUserInfo(updatedUser);
  
  // 记录积分使用
  addPointsRecord(POINTS_TYPES.USE, -points, description);
  
  return newPoints;
};

// 获取用户积分历史
export const getUserPointsHistory = () => {
  const userInfo = getUserInfo();
  if (!userInfo) return [];
  
  const allHistory = getPointsHistory();
  return allHistory.filter(record => record.userId === userInfo.id);
};

// 积分奖励规则
export const POINTS_REWARDS = {
  REGISTER: 100,     // 注册奖励
  ORDER_RATE: 0.002,  // 下单奖励比例（每500元1积分）
  REVIEW: 10,        // 评价奖励
  SIGN_IN: 5         // 签到奖励
};

// 计算订单积分奖励
export const calculateOrderPoints = (orderAmount) => {
  // 500元1积分，最少1积分
  const points = Math.max(1, Math.floor(orderAmount * POINTS_REWARDS.ORDER_RATE));
  return points;
};

// 注册奖励积分
export const giveRegisterPoints = () => {
  return addPoints(POINTS_REWARDS.REGISTER, POINTS_TYPES.REGISTER);
};

// 订单完成奖励积分
export const giveOrderPoints = (orderAmount) => {
  const points = calculateOrderPoints(orderAmount);
  return addPoints(points, POINTS_TYPES.ORDER, `订单完成奖励（订单金额¥${orderAmount.toFixed(2)}，¥500=1积分）`);
};

// 评价奖励积分
export const giveReviewPoints = (productName) => {
  return addPoints(POINTS_REWARDS.REVIEW, POINTS_TYPES.REVIEW, `评价商品：${productName}`);
};

// 签到奖励积分
export const giveSignInPoints = () => {
  return addPoints(POINTS_REWARDS.SIGN_IN, POINTS_TYPES.SIGN_IN);
}; 